<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>闭包实现myQuery</TITLE>
</HEAD>

<BODY>
<div id="lazy2009">hello,lazy2009!</div>
<div id="lazy_">hello,lazy_!</div>

<script>
/**
 * 委托模式实现myQuery
 */
	(function(win) {
		var slice = Array.prototype.slice;

		//使用闭包实现的类似jQuery的封装
		//selector只支持#id和tagName两种选择器，例如$("#id")，$("div")
		var myQuery = function(selector) {
			//私有成员，不让外界直接修改
			var arrDom = [];
			//调用document.getElementById或者document.getElementsByTagName获取元素集合
			if (selector.charAt(0) === '#') {
				arrDom[0] = document.getElementById(selector.substring(1));
			} else {
				var elements = document.getElementsByTagName(selector);
				for ( var i = 0; i < elements.length; i++) {
					arrDom[i] = elements[i];
				}
			}
			var myQueryObj = {};
			//导入myQuery对象公用方法
			var methods = myQuery.methods;
			//myQuery对象执行exec方法，会根据methodName委托到真正要执行的函数
			myQueryObj.exec = function(methodName) {
				return methods[methodName].apply(myQueryObj, [ arrDom ]
						.concat(slice.call(arguments, 1)));
			}
			return myQueryObj;
		};
		//myQuery导出到window全局作用域
		win.$ = win.myQuery = myQuery;

		//myQuery对象公用方法
		myQuery.methods = {
			version : function() {
				return "1.0";
			},
			text : function(arrDom, s) {
				if (!s) {
					return arrDom[0].innerText;
				} else {
					for ( var i = 0; i < arrDom.length; i++) {
						arrDom[i].innerText = s;
					}
				}
				return this;
			},
			each : function(arrDom, fn) {
				for ( var i = 0; i < arrDom.length; i++) {
					if (false === fn.call(arrDom[i], i, arrDom[i])) {
						break;
					}
				}
				return this;
			},
			get : function(arrDom, index) {
				if (!index) {
					return slice.call(arrDom);
				} else {
					return arrDom[i];
				}
			},
			size : function(arrDom) {
				return arrDom.length;
			}
		};
	})(window);
</script>
<script>
	//封装DOM API
	alert($("#lazy2009").exec("text"));
	alert($("#lazy_").exec("text"));
	//链式代码
	$("div").exec("text", "hello, world").exec("each", function(i, o) {
		alert(o.innerText + "==" + this.innerText);
	});
	alert($("div").exec("size"));
	//扩展方法
	if (!myQuery.methods.toArray) {
		myQuery.methods.toArray = function(arrDom) {
			return arrDom.slice(0);
		}
	}
	alert($("div").exec("toArray"));
</script>
</BODY>
</HTML>